﻿using System;

namespace TLang.Ast
{
    using Values;

    public class IntNum : Node
    {

        public String content;
        public int value;
        public int Base;


        public IntNum(String content, String file, int start, int end, int line, int col) : base(file, start, end, line, col)
        {
            this.content = content;

            int sign;
            if (content.StartsWith("+"))
            {
                sign = 1;
                content = content.Substring(1);
            }
            else if (content.StartsWith("-"))
            {
                sign = -1;
                content = content.Substring(1);
            }
            else
            {
                sign = 1;
            }

            if (content.StartsWith("0b"))
            {
                Base = 2;
                content = content.Substring(2);
            }
            else if (content.StartsWith("0x"))
            {
                Base = 16;
                content = content.Substring(2);
            }
            else if (content.StartsWith("0o"))
            {
                Base = 8;
                content = content.Substring(2);
            }
            else
            {
                Base = 10;
            }

            this.value = Convert.ToInt32(content, Base);
            if (sign == -1)
            {
                this.value = -this.value;
            }
        }


        public static IntNum parse(String content, String file, int start, int end, int line, int col)
        {
            try
            {
                return new IntNum(content, file, start, end, line, col);
            }
            catch (FormatException e)
            {
                return null;
            }
        }


        public override Value Interp(Scope s)
        {
            return new IntValue(value);
        }

        public override Value Typecheck(Scope s)
        {
            return Type.INT;
        }

        public override String ToString()
        {
            return value.ToString();
        }
    }
}
